const { makePassword, checkPassword } = require("../utils");

// 生成路由
const router = require("express").Router();

const { db } = require("../database");

// 导入用户登录状态检查的中间件
const { useAuthorization } = require("./base");
router.use(useAuthorization);

const multer = require("multer");
const { v4: uuid } = require("uuid");
const path = require("path");

// 配置上传文件的存储位置和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/avatars");
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, uuid() + ext);
  },
});

const upload = multer({ storage });

router
  // 查询用户信息
  .get("/", async (req, res) => {
    const user = await db.select(`SELECT * FROM user`);
    res.send({
      code: 200,
      message: "ok",
      result: user,
    });
  })
  // 新增用户
  .post("/", async (req, res) => {
    const { username, password, person } = req.body;

    const query =
      await db.findOne`select * from user where username = ${username}`;

    if (query) {
      res.send({
        code: -1,
        message: "用户已存在",
      });
      return;
    }
    const id =
      await db.insert`INSERT INTO user (username,password,person) VALUES (${username},${makePassword(
        password
      )},${person})`;
    const user = await db.select(`SELECT * FROM user WHERE id = ${id}`);
    res.send({
      code: 200,
      message: "用户创建成功",
      result: user,
    });
  })
  // 编辑用户信息（更新用户名） （不允许同时更新两个用户名)
  .post("/infos", upload.single("avatar"), async (req, res) => {
    const a = req.body;
    const id = req.user.id;
    // console.log(id);
    const query = `select * from user where id = ${id}`;
    if (!query) {
      return res.send({ code: -1, message: "该用户信息不存在！" });
    }

    await db.run`update user set avatar = ${req.file?.filename} where id = ${id}`;
    // console.log(req.file?.filename);

    await db.run`update person set name = ${a.name}, phone = ${a.phone}, address = ${a.address} where id = ${id}`;
    user =
      await db.findOne`select * from user inner join person on user.person = person.id where user.id = ${id}`;
    res.send({
      code: 200,
      message: "用户修改成功",
      result: {
        user: {
          id: user.id,
          name: user.name,
          sex: user.sex,
          address: user.address,
          duty: user.duty,
          phone: user.phone,
          description: user.description,
          org: user.org,
          avatar: "http://localhost:3333/avatars/" + user.avatar,
        },
      },
    });
    // console.log(user);
  })
  // 修改密码
  .post("/changePassword", async (req, res) => {
    // console.log(1);
    const { oldPassword, password } = req.body;
    // console.log(req.user);
    if (!checkPassword(oldPassword, req.user.password)) {
      return res.send({
        code: -1,
        message: "原密码不正确，不能执行修改密码操作！",
      });
    }
    if (oldPassword == password) {
      return res.send({
        code: -1,
        message: "新密码和原密码不能相同！",
      });
    }
    await db.run("update user set password = ? where id = ?", [
      makePassword(password),
      req.user.id,
    ]);

    res.send({
      code: 200,
      message: "密码修改成功！",
    });
  })
  // 重置密码
  .put("/:tid", async (req, res) => {
    const { password } = req.body;
    const query = `select * from user where id = ${req.params.tid}`;
    if (!query) {
      return res.send({ code: -1, message: "该用户信息不存在！" });
    }
    await db.run`update user set password = ${makePassword(
      password
    )} where id = ${req.params.tid}`;
    user = await db.findOne`select * from user where id = ${req.params.tid}`;
    res.send({
      code: 200,
      message: "密码重置成功",
      result: user,
    });
  })
  // 删除用户
  .delete("/:tid", async (req, res) => {
    const query =
      await db.findOne`select * from user where id = ${req.params.tid}`;
    if (!query) {
      return res.send({ code: -1, message: "该用户信息不存在！" });
    }
    // 删除 role 记录
    await db.run`delete from user where id = ${req.params.tid}`;
    res.send({
      code: 200,
      message: "删除成功",
    });
  });

const registerRouter = (app) => app.use("/user", router);
module.exports = { registerRouter };
